<template>
  <div>
    <common-heads />
    <img src="https://t7.baidu.com/it/u=737555197,308540855&fm=193&f=GIF" alt="">
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
        { required: true, message: '请填写用户名' },
        /*
          //通过函数进行校验
        {
          validator:(value)=>{
            if(value==='时光'){
              return true
            }else{
              return false
            }
          },
          message:'请输入时光'
        }
        // 通过正则验证
        {
          pattern:/\d{4,8}/,
          message:'请按照规则填写'
          } */
        ]"
      />
      <van-field
        v-model="user.pwd"
        type="password"
        name="pwd"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <!-- 登录表单 -->
    <van-button @click="$router.push('/register')">到注册页</van-button>
  </div>
</template>

<script>
import CommonHeads from '../../components/CommonHeads.vue'
import { doLogin } from '_api'
import { Toast } from 'vant'
export default {
  components: {
    CommonHeads
  },
  data () {
    return {
      user: {
        username: '',
        pwd: ''
      }
    }
  },
  methods: {
    onSubmit (params) {
      // 提交表单事件
      doLogin({
        deviceId: '111',
        deviceName: '222',
        ...this.user
      }).then(res => {
        if (res.data.code === 0) {
          Toast({
            type: 'success',
            message: '登录成功',
            duration: 1000,
            onClose: () => {
              // 判断
              localStorage.setItem('token', res.data.data.token)
              if (this.$route.query.from) {
                this.$router.replace(this.$route.query.from)
              } else {
                this.$router.replace('/home')
              }
            }
          })
        } else {
          Toast({
            type: 'fail',
            message: res.data.msg
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
img{
  width: 100%;
  margin-top: 46px;
}
.van-form{
  margin-top: -8px;
}
</style>
